<script lang="ts" setup>
import {
  IconAddCircle,
  IconRefreshLine,
  IconEye,
  VButton,
  VCard,
  VPageHeader,
  VPagination,
  VSpace,
  VTag,
  VEntity,
  VEntityField,
  VStatusDot,
  VDropdownItem,
  VLoading,
  VEmpty,
  VAvatar,
  Dialog,
  Toast,
} from "@halo-dev/components";
import SearchInput from "@console/components/input/SearchInput.vue";
import { FormKit } from "@formkit/vue";
import { computed, onMounted, ref, watch } from "vue";
import type { Product, ProductType } from "@console/types";
import { productApiClient, productTypeApiClient } from "@console/api/product";
import { formatDatetime } from "@console/utils/date";
import ProductEditingModal from "./ProductEditingModal.vue";
import ProductDetailModal from "./ProductDetailModal.vue";

const products = ref<Product[]>([]);
const productTypes = ref<ProductType[]>([]);
const loading = ref(false);
const total = ref(0);
const page = ref(1);
const size = ref(20);
const keyword = ref("");
const selectedProductTypeRef = ref<string>("");
const editingModal = ref(false);
const detailModal = ref(false);
const selectedProduct = ref<Product>();

const handleFetchProducts = async () => {
  try {
    loading.value = true;

    // 构建请求参数，排除空的productTypeRef
    const params: any = {
      page: page.value,
      size: size.value,
      keyword: keyword.value,
    };
    
    // 只有当selectedProductTypeRef有值时才添加到参数中
    if (selectedProductTypeRef.value) {
      params.productTypeRef = selectedProductTypeRef.value;
    }

    console.log('📋 Product API 请求参数:', params);
    console.log('🔗 实际API URL:', '/apis/content.halo.run/v1alpha1/products?' + new URLSearchParams(params).toString());
    
    const { data } = await productApiClient.listProducts(params);

    console.log(`✅ 获取到 ${data.items.length} 个产品，总计: ${data.total}`);
    console.log('📊 产品详情:', data.items.map(p => ({ 
      name: p.spec?.displayName || p.displayName || '未知产品', 
      productTypeRef: p.spec?.productTypeRef || p.productTypeRef || '',
      id: p.metadata?.name || p.name || ''
    })));
    
    // 检查过滤效果
    if (params.productTypeRef) {
      const expectedType = params.productTypeRef;
      const correctlyFiltered = data.items.filter(p => (p.spec?.productTypeRef || p.productTypeRef) === expectedType);
      const incorrectlyIncluded = data.items.filter(p => (p.spec?.productTypeRef || p.productTypeRef) !== expectedType);
      
      console.log(`🎯 过滤检查: 期望类型="${expectedType}"`);
      console.log(`✅ 正确过滤: ${correctlyFiltered.length} 个产品`);
      
      if (incorrectlyIncluded.length > 0) {
        console.warn(`⚠️ 过滤异常: 发现 ${incorrectlyIncluded.length} 个不应该出现的产品:`);
        console.warn('异常产品:', incorrectlyIncluded.map(p => ({ 
          name: p.spec?.displayName || p.displayName || '未知产品', 
          actualType: p.spec?.productTypeRef || p.productTypeRef || ''
        })));
      }
    }

    products.value = data.items;
    total.value = data.total;
  } catch (error) {
    console.error("Failed to fetch products", error);
  } finally {
    loading.value = false;
  }
};

const handleFetchProductTypes = async () => {
  try {
    const { data } = await productTypeApiClient.listProductTypes({
      page: 0,
      size: 0,
    });
    
    console.log('🏷️ 获取到的产品类型数据:', data);
    console.log('🏷️ 产品类型数组:', data.items);
    if (data.items && data.items.length > 0) {
      console.log('🏷️ 第一个产品类型结构:', data.items[0]);
      console.log('🏷️ 是否有spec字段:', !!data.items[0].spec);
      console.log('🏷️ 是否有displayName:', !!data.items[0].spec?.displayName);
    }
    
    productTypes.value = data.items;
  } catch (error) {
    console.error("Failed to fetch product types", error);
  }
};

const handleOpenEditingModal = (product?: Product) => {
  selectedProduct.value = product;
  editingModal.value = true;
};

const handleOpenDetailModal = (product: Product) => {
  selectedProduct.value = product;
  detailModal.value = true;
};

const onEditingModalClose = () => {
  selectedProduct.value = undefined;
  editingModal.value = false;
  handleFetchProducts();
};

const onDetailModalClose = () => {
  selectedProduct.value = undefined;
  detailModal.value = false;
};

const handleDelete = async (product: Product) => {
  Dialog.warning({
    title: "确定要删除该产品吗？",
    description: "删除之后将无法恢复",
    confirmType: "danger",
    onConfirm: async () => {
      try {
        await productApiClient.deleteProduct({
          name: product.metadata.name,
        });

        Toast.success("删除成功");
        await handleFetchProducts();
      } catch (error) {
        console.error("Failed to delete product", error);
      }
    },
  });
};

const handlePaginationChange = ({
  page: newPage,
  size: newSize,
}: {
  page: number;
  size: number;
}) => {
  page.value = newPage;
  size.value = newSize;
  handleFetchProducts();
};

const getProductTypeName = (productTypeRef: string) => {
  const productType = productTypes.value.find(
    (type) => (type.metadata?.name || type.name) === productTypeRef
  );
  return productType?.spec?.displayName || productType?.displayName || productTypeRef;
};

const formatPrice = (price?: number) => {
  if (price === undefined || price === null) return "-";
  return `¥${price.toFixed(2)}`;
};

watch([() => keyword.value, () => selectedProductTypeRef.value], ([newKeyword, newProductTypeRef]) => {
  console.log('🎯 过滤条件变更:', { 
    keyword: newKeyword, 
    productTypeRef: newProductTypeRef,
    isEmptyProductTypeRef: !newProductTypeRef
  });
  page.value = 1;
  handleFetchProducts();
});

onMounted(() => {
  handleFetchProductTypes();
  handleFetchProducts();
});
</script>

<template>
  <VPageHeader title="产品管理">
    <template #icon>
      <IconAddCircle class="mr-2 self-center" />
    </template>
    <template #actions>
      <VSpace>
        <VButton
          v-permission="['system:products:manage']"
          type="secondary"
          @click="handleFetchProducts"
        >
          <template #icon>
            <IconRefreshLine class="h-4 w-4" />
          </template>
          刷新
        </VButton>
        <VButton
          v-permission="['system:products:manage']"
          type="primary"
          @click="handleOpenEditingModal()"
        >
          <template #icon>
            <IconAddCircle class="h-4 w-4" />
          </template>
          新建
        </VButton>
      </VSpace>
    </template>
  </VPageHeader>

  <div class="m-0 md:m-4">
    <VCard :body-class="['!p-0']">
      <template #header>
        <div class="block w-full bg-gray-50 px-4 py-3">
          <div class="relative flex flex-col items-start sm:flex-row sm:items-center">
            <div class="flex w-full flex-1 flex-col gap-2 sm:flex-row sm:items-center">
              <div class="w-full sm:w-auto">
                <SearchInput
                  v-model="keyword"
                  placeholder="输入关键词搜索"
                />
              </div>
              <div class="w-full sm:w-auto">
                <FormKit
                  v-model="selectedProductTypeRef"
                  placeholder="选择产品类型"
                  type="select"
                  :options="[
                    { label: '全部类型', value: '' },
                    ...productTypes.map((type) => ({
                      label: type.spec?.displayName || type.displayName || '未知类型',
                      value: type.metadata?.name || type.name || '',
                    })),
                  ]"
                ></FormKit>
              </div>
            </div>
          </div>
        </div>
      </template>

      <VLoading v-if="loading" />
      <Transition v-else-if="!products.length" appear name="fade">
        <VEmpty
          message="你可以尝试刷新或者新建产品"
          title="当前没有产品"
        >
          <template #actions>
            <VSpace>
              <VButton @click="handleFetchProducts">刷新</VButton>
              <VButton
                v-permission="['system:products:manage']"
                type="primary"
                @click="handleOpenEditingModal()"
              >
                <template #icon>
                  <IconAddCircle class="h-4 w-4" />
                </template>
                新建产品
              </VButton>
            </VSpace>
          </template>
        </VEmpty>
      </Transition>
      <Transition v-else appear name="fade">
        <div>
          <div class="px-4 pt-4 pb-2">
            <div class="flex items-center justify-between">
              <div class="flex items-center gap-2">
                <span class="text-sm font-medium text-gray-700">
                  共 {{ total }} 项
                </span>
              </div>
            </div>
          </div>
          <div class="overflow-hidden">
            <div class="divide-y divide-gray-100">
              <VEntity
                v-for="(product, index) in products"
                :key="index"
                :is-selected="false"
              >
                <template #start>
                  <VEntityField>
                    <template #start>
                      <VAvatar
                        v-if="product.spec.images?.length"
                        :src="product.spec.images[0]"
                        :alt="product.spec.displayName"
                        size="md"
                        circle
                      />
                      <VAvatar
                        v-else
                        :alt="product.spec.displayName"
                        size="md"
                        circle
                      />
                    </template>
                    <template #title>
                      <div class="flex items-center gap-2">
                        <span>{{ product.spec.displayName }}</span>
                        <VStatusDot
                          v-if="product.spec.published"
                          state="success"
                          text="已发布"
                        />
                        <VStatusDot
                          v-else
                          state="default"
                          text="未发布"
                        />
                      </div>
                    </template>
                    <template #description>
                      <div class="flex flex-col gap-1">
                        <div class="text-xs text-gray-500">
                          {{ product.spec.description || '暂无描述' }}
                        </div>
                        <div class="flex items-center gap-2">
                          <VTag size="sm">
                            {{ getProductTypeName(product.spec?.productTypeRef || product.productTypeRef || '') }}
                          </VTag>
                          <VTag v-if="product.spec.price" size="sm">
                            {{ formatPrice(product.spec.price) }}
                          </VTag>
                          <VTag v-if="product.spec.minOrderQuantity" size="sm">
                            起订量: {{ product.spec.minOrderQuantity }}
                          </VTag>
                        </div>
                      </div>
                    </template>
                  </VEntityField>
                </template>
                <template #end>
                  <VEntityField>
                    <template #description>
                      <div class="flex flex-col items-end gap-1">
                        <span class="text-xs text-gray-500">
                          {{ formatDatetime(product.metadata.creationTimestamp) }}
                        </span>
                      </div>
                    </template>
                  </VEntityField>
                </template>
                <template #dropdownItems>
                  <VDropdownItem @click="handleOpenDetailModal(product)">
                    <template #icon>
                      <IconEye class="h-4 w-4" />
                    </template>
                    查看详情
                  </VDropdownItem>
                  <VDropdownItem
                    v-permission="['system:products:manage']"
                    @click="handleOpenEditingModal(product)"
                  >
                    修改
                  </VDropdownItem>
                  <VDropdownItem
                    v-permission="['system:products:manage']"
                    type="danger"
                    @click="handleDelete(product)"
                  >
                    删除
                  </VDropdownItem>
                </template>
              </VEntity>
            </div>
          </div>
          <div class="bg-white px-4 py-4">
            <VPagination
              v-model:page="page"
              v-model:size="size"
              :page-label="'页'"
              :size-label="'条 / 页'"
              :total="total"
              :size-options="[20, 30, 50, 100]"
              @change="handlePaginationChange"
            />
          </div>
        </div>
      </Transition>
    </VCard>
  </div>

  <ProductEditingModal
    v-model:visible="editingModal"
    :product="selectedProduct"
    @close="onEditingModalClose"
  />

  <ProductDetailModal
    v-model:visible="detailModal"
    :product="selectedProduct"
    @close="onDetailModalClose"
  />
</template>